package com.qf.servlet;

import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author AzureSky_X
 * @Date 2021/1/6 8:54
 * @Version 1.0
 * 用户控制
 */
@WebServlet("/login")
public class UserController extends HttpServlet {
    private UserService service=new UserServiceImpl();
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决中文乱码问题
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        PrintWriter printWriter=response.getWriter();
        String errorMsg="";

        //获取验证码
        String pageCode = request.getParameter("mycode");
        HttpSession session = request.getSession();
        String sessionCode = (String) session.getAttribute("sessionCode");

        //校验验证码
        if (null != pageCode&&pageCode.equalsIgnoreCase(sessionCode)){
            //验证码正确
            String username = request.getParameter("username");
            String password = request.getParameter("password");


            try {
                User user = service.login(username, password);
//                request.setAttribute("user", user);
//                request.getRequestDispatcher("showname").forward(request, response);
                //登录信息保存到session
                session.setAttribute("user",user);
                //登录成功后查看用户所有信息
                response.sendRedirect(request.getContextPath()+"/user/list");
                return;
            }catch (RuntimeException e){
                errorMsg="该用户状态异常，请联系管理员！！";
            }
            catch (Exception e) {
                e.printStackTrace();
//                request.setAttribute("errorMsg", e.getMessage());
//                request.getRequestDispatcher("error").forward(request, response);
                errorMsg="用户名或密码错误！";

            }


        }else {
            errorMsg="验证码错误！";
        }
        //运行到这里代表登录失败，重定向到登录页面并显示失败信息
        //location.href="/URL地址"
        printWriter.write("<script>alert('"+errorMsg+"');location.href='"+request.getContextPath()+"/login.jsp';</script>");




    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}